'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/auth-context'
import { useToastHelpers } from '@/components/ui/toast'
import { Heart } from 'lucide-react'
import { Button } from '@/components/ui/button'

interface FavoriteButtonProps {
  toolId: string
  size?: 'sm' | 'md' | 'lg'
  variant?: 'default' | 'outline' | 'ghost'
  showText?: boolean
}

export function FavoriteButton({
  toolId,
  size = 'md',
  variant = 'outline',
  showText = true
}: FavoriteButtonProps) {
  const { user: authUser } = useAuth()
  const { success, error: showError } = useToastHelpers()
  const [isFavorited, setIsFavorited] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [message, setMessage] = useState<string | null>(null)

  useEffect(() => {
    if (authUser) {
      checkFavoriteStatus()
    }
  }, [toolId, authUser])

  const checkFavoriteStatus = async () => {
    if (!authUser) return

    try {
      const response = await fetch(`/api/tools/${toolId}/favorite?userId=${authUser.id}`)
      const result = await response.json()

      if (response.ok) {
        setIsFavorited(result.data.favorited)
      }
    } catch (error) {
      console.error('检查收藏状态失败:', error)
    }
  }

  const handleToggleFavorite = async () => {
    if (!authUser) {
      showError('请先登录', '登录后即可收藏喜欢的工具')
      return
    }

    setIsLoading(true)
    setMessage(null)

    try {
      if (isFavorited) {
        // 取消收藏
        const response = await fetch(`/api/tools/${toolId}/favorite?userId=${authUser.id}`, {
          method: 'DELETE'
        })

        const result = await response.json()

        if (response.ok) {
          setIsFavorited(false)
          success('已取消收藏')
        } else {
          showError('操作失败', result.error || '取消收藏失败，请重试')
        }
      } else {
        // 添加收藏
        const response = await fetch(`/api/tools/${toolId}/favorite`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ userId: authUser.id })
        })

        const result = await response.json()

        if (response.ok) {
          setIsFavorited(true)
          success('收藏成功', '已添加到我的收藏')
        } else {
          showError('操作失败', result.error || '收藏失败，请重试')
        }
      }
    } catch (error) {
      showError('网络错误', '请检查网络连接后重试')
    } finally {
      setIsLoading(false)
    }
  }

  const sizeClasses = {
    sm: 'h-4 w-4',
    md: 'h-5 w-5',
    lg: 'h-6 w-6'
  }

  return (
    <div className="relative">
      <Button
        variant={variant}
        size={size}
        onClick={handleToggleFavorite}
        disabled={isLoading}
        className={`flex items-center gap-2 ${
          isFavorited ? 'text-red-500 border-red-200 hover:bg-red-50' : ''
        }`}
      >
        <Heart 
          className={`${sizeClasses[size]} transition-colors ${
            isFavorited ? 'fill-red-500 text-red-500' : 'text-gray-500'
          }`}
        />
        {showText && (
          <span>
            {isLoading ? '处理中...' : isFavorited ? '已收藏' : '收藏'}
          </span>
        )}
      </Button>

      {/* 消息提示 */}
      {message && (
        <div className="absolute top-full left-0 mt-2 px-3 py-1 bg-gray-900 text-white text-xs rounded-md whitespace-nowrap z-10">
          {message}
        </div>
      )}
    </div>
  )
}
